package com.qiwo.bpm.controller;

import com.qiwo.bpm.domain.FlowDefinition;
import com.qiwo.bpm.service.FlowDefinitionService;
import com.qiwo.bpm.service.FlowFunctionService;
import com.qiwo.common.utils.FileUtil;
import com.qiwo.common.utils.Result;
import com.qiwo.common.utils.ZipCompress;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping({"/bpm/definition/"})
public class FlowDefinitionController {

    @Autowired
    private FlowDefinitionService flowDefinitionManager;

    @Autowired
    private FlowFunctionService flowFunctionManager;

    @ApiOperation("创建流程")
    @GetMapping("/create")
    public String create(Model model, Integer flowType)
            throws Exception
    {
        String functions = this.flowFunctionManager.getFunctions(flowType);
        model.addAttribute("functions", functions);
        return "pub/bpm/flexflow/JbpmWorkFlow";
    }

    @GetMapping("/saveFlow")
    @ResponseBody
    public String save(String id, String flowxml, Integer flowTypeID)
            throws Exception
    {
        this.flowDefinitionManager.save(id, flowxml, flowTypeID);
        return "{\"success\":true}";
    }

    @GetMapping({"import"})
    @ResponseBody
    public String doImport(Model model, HttpServletRequest request, String typeId)
            throws Exception
    {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        Map files = multipartRequest.getFileMap();

        if (files.size() > 0) {
            Iterator fileNames = multipartRequest.getFileNames();
            String fileName = (String)fileNames.next();
            CommonsMultipartFile file = (CommonsMultipartFile)files.get(fileName);
            String tmpFile = System.getProperty("java.io.tmpdir") + File.separator + new Date().getTime() + ".zip";
            FileUtil.writeFile(tmpFile, file.getBytes());
            this.flowDefinitionManager.doImport(tmpFile, typeId);
        }
        return "{\"success\":true}";
    }

    @GetMapping({"export"})
    public void doExport(HttpServletResponse response, String ids)
            throws Exception
    {
        String[] idArr = ids.split(",");
        String tmpdir = System.getProperty("java.io.tmpdir");
        String zipDir = tmpdir + "bpm_export" + new Date().getTime() + File.separator;
        new File(zipDir).mkdir();
        for (String id : idArr) {
            FlowDefinition def = (FlowDefinition)this.flowDefinitionManager.selectById(id);
            FileUtil.writeFile(zipDir + def.getId() + ".xml", def.getFlowXml().getBytes());
        }

        String fileName = "工作流定义备份(" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ").zip";
        String zipFile = tmpdir + File.separator + fileName;
        ZipCompress.zipFileWidthApacheZip(zipDir, zipFile, Boolean.valueOf(false));
        FileUtil.download(response, zipFile, fileName, "application/zip");

        FileUtil.delAllFile(zipFile);
        FileUtil.delAllFile(zipDir);
    }

    @GetMapping({"modifyFlow"})
    public String modify(HttpServletRequest request, String id)
            throws Exception
    {
        FlowDefinition flowDefinition = (FlowDefinition)this.flowDefinitionManager.selectById(id);

        String flowxml = this.flowDefinitionManager.flowXmlEnter(flowDefinition.getFlowXml());
        flowDefinition.setFlowXml(flowxml);
        request.setAttribute("flowDefinition", flowDefinition);
        String functions = this.flowFunctionManager.getFunctions(flowDefinition.getFlowType());
        request.setAttribute("functions", functions);
        return "pub/bpm/flexflow/JbpmWorkFlow";
    }

    @GetMapping({"copyFlow"})
    @ResponseBody
    public Result copyDefinition(String id, int copies, Integer type)
            throws Exception
    {
        this.flowDefinitionManager.copyDefinition(id, copies, type);
        return Result.ok();
    }

    @RequestMapping({"detailFlow"})
    public String detailFlow(Model model, String id)
            throws Exception
    {
        FlowDefinition flowDefinition = (FlowDefinition)this.flowDefinitionManager.selectById(id);

        String flowxml = this.flowDefinitionManager.flowXmlEnter(flowDefinition.getFlowXml());
        flowDefinition.setFlowXml(flowxml);
        model.addAttribute("flowxml", flowxml);
        model.addAttribute("flowDefinition", flowDefinition);
        return "pub/bpm/flexflow/FlowTrask";
    }

    @RequestMapping({"flowIssue"})
    @ResponseBody
    public Result flowIssue(String ids)
            throws Exception
    {
        this.flowDefinitionManager.flowIssue(ids.split(","), 1);
        return Result.ok();
    }

    @RequestMapping({"flowUnIssue"})
    @ResponseBody
    public Result flowUnIssue(String ids) throws Exception
    {
        this.flowDefinitionManager.flowIssue(ids.split(","), 0);
        return Result.ok();
    }
}
